import { SET_ROUTE_TREE } from '@/store/actionTypes';
import { IState } from '@/store/state';
import { IRoute } from '@/typings';
import { Router, RouteRecordRaw } from 'vue-router';
import { Store } from 'vuex';

//创建动态路由规则列表
function generateRouter(routeTree: IRoute[]) {
  let newRoutes = routeTree.map((route) => {
    //创建规则对象
    let _route: RouteRecordRaw = {
      path: route.path,
      name: route.name,
      component: () =>
        import(
          `/* webpackChunkName: "${route.name}" */@/views/${route.name}.vue`
        ),
      children: []
    };

    //存在数据树时
    if (route.children) {
      _route.children = generateRouter(route.children);
    }

    return _route;
  });

  return newRoutes;
}

//设置路由守卫
export function routerBeforeEach(router: Router, store: Store<IState>) {
  router.beforeEach(async (to, from, next) => {
    if (!store.state.hasAuth) {
      await store.dispatch(SET_ROUTE_TREE);
      const newRoutes = generateRouter(store.state.routeTree);
      newRoutes.forEach((route) => router.addRoute(route));
      next({ path: to.path });
    } else {
      next();
    }
  });
}
